require 'digest/sha1'
class User < ActiveRecord::Base
  validates_presence_of :name
  validates_uniqueness_of :name

  # 不需要生成散列码
  attr_accessor :password_confirmation
  validates_confirmation_of :password

  def validate
    errors.add_to_base("Missing password") if hashed_password.blank?
  end

  # 只读方法
  def password
    @password
  end
  #可写方法
  def password=(pwd)
    @password = pwd
    return if pwd.blank?
    create_new_salt
    self.hashed_password =User.encrypted_password(self.password, self.salt)
  end

  # 验证用户的输入及密码
  def self.authentication(name, password)
    # 动态创建一个查找方法
    user = self.find_by_name(name)
    if user
      expected_password = encrypted_password(password, user.salt)
      if user.hashed_password != expected_password
        user = nil
      end
    end
    user
  end

  # self. 意思是调用当前对象的salt方法
  def create_new_salt
    self.salt =self.object_id.to_s + rand.to_s
  end

  # 提供一个钩子方法，对delete方法进行监视
  def after_destroy
    if User.count.zero?
      raise "Can't delete last user"
    end
  end

  private
  # 将密码加密
  def self.encrypted_password(password, salt)
    string_to_hash  = password + "cash" + salt  # cash makes it harder be crack
    Digest::SHA1.hexdigest(string_to_hash)
  end

end